<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="companyId">
          <el-input
              v-model="queryParams.companyId"
              placeholder="公司编号"
              @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
              v-model="queryParams.status"
              placeholder="全部"
              clearable
              class="!w-[100px]"
          >
            <el-option :value="1" label="正常" />
            <el-option :value="0" label="禁用" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button class="filter-item" type="primary" @click="handleQuery">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="resetQuery"> <i-ep-refresh />重置 </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button
            v-hasPerm="['biz:code:add']"
            type="success"
            @click="openDialog( undefined)"
        ><i-ep-plus />新增</el-button
        >
        <el-button
            v-hasPerm="['biz:code:delete']"
            type="danger"
            :disabled="ids.length === 0"
            @click="handleDelete()"
        ><i-ep-delete />删除
        </el-button>
      </template>

      <el-table
          v-loading="loading"
          :data="codeList"
          row-key="id"
          default-expand-all
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="companyId" label="公司编号" min-width="100" />
        <el-table-column prop="codText" label="代码文本" min-width="100" />
        <el-table-column prop="createBy" label="创建人id" min-width="100" />
        <el-table-column prop="updateBy" label="修改人id" min-width="100" />
        <el-table-column prop="remark" label="备注" min-width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status == 1" type="success">正常</el-tag>
            <el-tag v-else type="info">禁用</el-tag>
          </template>
        </el-table-column>


        <el-table-column label="操作" fixed="right" align="left" width="200">
          <template #default="scope">
            <el-button
                v-hasPerm="['biz:code:add']"
                type="primary"
                link
                size="small"
                @click.stop="openDialog(undefined)"
            ><i-ep-plus />新增
            </el-button>
            <el-button
                v-hasPerm="['biz:code:edit']"
                type="primary"
                link
                size="small"
                @click.stop="openDialog(scope.row.companyId)"
            ><i-ep-edit />编辑
            </el-button>
            <el-button
                v-hasPerm="['biz:code:delete']"
                type="primary"
                link
                size="small"
                @click.stop="handleDelete(scope.row.id)"
            >
              <i-ep-delete />删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog
        v-model="dialog.visible"
        :title="dialog.title"
        width="600px"
        @closed="closeDialog"
    >
      <el-form
          ref="codeFormRef"
          :model="formData"
          :rules="rules"
          label-width="80px"
      >
        <el-form-item label="公司编号" prop="companyId">
          <el-input v-model="formData.companyId" placeholder="请输入公司编号" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="代码文本" prop="codText">
          <el-input v-model="formData.codText" placeholder="请输入代码文本" />
        </el-form-item>
        <el-form-item label="创建人id" prop="createBy">
          <el-input v-model="formData.createBy" placeholder="请输入创建人id" />
        </el-form-item>
        <el-form-item label="修改人id" prop="updateBy">
          <el-input v-model="formData.updateBy" placeholder="请输入修改人id" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit"> 确 定 </el-button>
          <el-button @click="closeDialog"> 取 消 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  deleteCode,
  updateCode,
  addCode,
  listCodes,
} from "@/api/code";
import { CodeVO, CodeForm, CodeQuery } from "@/api/code/types";

defineOptions({
  name: "Code",
  inheritAttrs: false,
});

const queryFormRef = ref(ElForm);
const codeFormRef = ref(ElForm);

const loading = ref(false);
const ids = ref<number[]>([]);
const dialog = reactive({
  title: "",
  visible: false,
});

const queryParams = reactive<CodeQuery>({});
const codeList = ref<CodeVO[]>([]);

const formData = reactive<CodeForm>({
  id: undefined,
  companyId: undefined,
  status: 1,
});

const rules = reactive({
  companyId: [
    { required: true, message: "公司编号不能为空", trigger: "blur" },
  ],
  status: [
    { required: true, message: "状态不能为空", trigger: "blur" },
  ],
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  listCodes(queryParams).then(({ data }) => {
    codeList.value = data;
    loading.value = false;
  });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}
async function openDialog(companyId?: number) {
  dialog.visible = true;
  if (companyId) {
    dialog.title = "修改";
    listCodes({ companyId }).then(({ data }) => {
      if (data && data.length > 0) {
        const { companyId: receivedCompanyId, codText, createBy, updateBy, status, remark,id } = data[0];
        formData.companyId = receivedCompanyId;
        formData.codText = codText;
        formData.createBy = createBy;
        formData.updateBy = updateBy;
        formData.status = status;
        formData.remark = remark;
        formData.id= id;
      }
    });
  } else {
    dialog.title = "新增";
    // 保持新增操作的初始化逻辑
    formData.companyId = undefined;
    formData.codText = "";
    formData.createBy = undefined;
    formData.updateBy = undefined;
    formData.remark = "";
  }
}



/** 表单提交 */
function handleSubmit() {
  codeFormRef.value.validate((valid: any) => {
    if (valid) {
      const codeId = formData.id;
      loading.value = true;
      if (codeId) {
        updateCode(codeId, formData)
            .then(() => {
              ElMessage.success("修改成功");
              closeDialog();
              handleQuery();
            })
            .finally(() => (loading.value = false));
      } else {
        addCode(formData)
            .then(() => {
              ElMessage.success("新增成功");
              closeDialog();
              handleQuery();
            })
            .finally(() => (loading.value = false));
      }
    }
  });
}

function handleDelete(codeId?: number) {
  const codeIds = [codeId || ids.value].join(",");

  if (!codeIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm(`确认删除已选中的数据项?`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    deleteCode(codeIds).then(() => {
      ElMessage.success("删除成功");
      resetQuery();
    });
  });
}

/** 关闭弹窗 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

/** 重置表单  */
function resetForm() {
  codeFormRef.value.resetFields();
  codeFormRef.value.clearValidate();

  formData.id = undefined;
  formData.companyId = undefined;
  formData.status = 1;
}

onMounted(()=> {
  handleQuery();
});
</script>